package com.hboxs.asl.controller.app.member;

import com.gexin.fastjson.JSONObject;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.net.URL;

@Controller(value = "appIOSPointController")
@RequestMapping(value = "/app/m/iosPoint")
public class IOSPointController extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "yiYuanTradeServiceImpl")
    private YiYuanTradeService yiYuanTradeService;
    @Resource(name = "questionServiceImpl")
    private QuestionService questionService;
    @Resource(name = "globalConfigServiceImpl")
    private GlobalConfigService globalConfigService;
    @Resource(name = "courseTradeServiceImpl")
    private CourseTradeService courseTradeService;
    @Resource(name = "tradeServiceImpl")
    private TradeService tradeService;

    /**
     * 一元支付查看答案支付
     * @return
     */
    @RequestMapping(value = "/yiyuan", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage yiyuan(String sn) {
        System.out.println("一元支付" + sn);
        try {
            //1. 获取系统yiyuanTrade
            YiYuanTrade yiYuanTrade = yiYuanTradeService.findBySn(sn);
            if (yiYuanTrade == null) {
                return JsonMessage.error("订单不存在!");
            }
            //2.yiyuanTrade是否属于当前用户
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (yiYuanTrade.getBuyer() != member) {
                return JsonMessage.error("订单不属于该用户!");
            }
            //3.判断yiyuanTrade是否支付
            if (yiYuanTrade.getPaymentStatus() == YiYuanTrade.PaymentStatus.paid) {
                return JsonMessage.success("订单已支付!");
            }

            //4.判断积分是否足够
            GlobalConfig globalConfig = globalConfigService.getUniqueness();

            if (globalConfig != null) {
                if (globalConfig.getPercentage() != null) {
                    //需要的积分数
                    BigDecimal point = yiYuanTrade.getPrice().multiply(globalConfig.getPercentage());
                    if (member.getPoint().compareTo(point) >= 0) {  //积分足够
                        BigDecimal splitIntegral = point.divide(BigDecimal.valueOf(2));
                        //用户提成
                        member.setPoint(member.getPoint().subtract(splitIntegral));
                        //提问者
                        Question question = questionService.find(yiYuanTrade.getQuestionId());
                        if (question != null) {
                            Member asker = question.getMember();
                            //我的收入
                            asker.setEarnings(member.getEarnings().add(splitIntegral.divide(globalConfig.getPercentage())));
                            memberService.update(asker);
                        }
                        //生成财务记录（还有用户分成）
                        yiYuanTradeService.dealYiYuanTrade(yiYuanTrade);
                    } else {
                        return JsonMessage.error("积分不足");
                    }
                } else {
                    return JsonMessage.error("支付失败");
                }
            } else {
                return JsonMessage.error("支付失败");
            }

            return JsonMessage.success();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 提问支付
     * @return
     */
    @RequestMapping(value = "/ask", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage ask(String sn) {
        System.out.println("提问支付" + sn);
        try {
            //1. 获取系统question
            Question question = questionService.findBySn(sn);
            if (question == null) {
                return JsonMessage.error("易问易答不存在");
            }
            //2.question是否属于当前用户
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (question.getMember() != member) {
                return JsonMessage.error("易问易答不属于该用户!");
            }
            //3.判断question是否支付
            if (question.getPaymentStatus() == Question.PaymentStatus.paid) {
                return JsonMessage.error("易问易答已支付!");
            }

            //4.使用积分支付
            GlobalConfig globalConfig = globalConfigService.getUniqueness();
            if (globalConfig != null) {
                if (globalConfig.getPercentage() != null) {
                    //需要支付的积分
                    BigDecimal point = question.getPayPrice().multiply(globalConfig.getPercentage());
                    if (member.getPoint().compareTo(point) >= 0) {  //积分足够
                        member.setPoint(member.getPoint().subtract(point));
                        memberService.update(member);
                        //生成财务记录
                        questionService.dealQuestion(question);
                    } else {
                        return JsonMessage.error("积分不足");
                    }
                } else {
                    return JsonMessage.error("支付失败");
                }
            } else {
                return JsonMessage.error("支付失败");
            }
            return JsonMessage.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 购买课程支付
     * @param sn
     * @return
     */
    @RequestMapping(value = "/coursePay", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage coursePay(String sn) {
        System.out.println("购买课程" + sn);
        try {
            //1. 获取courseTrade
            CourseTrade courseTrade = courseTradeService.findBySn(sn);
            if (courseTrade == null) {
                return JsonMessage.error("订单不存在!");
            }
            //2.courseTrade是否属于当前用户
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (courseTrade.getBuyer() != member) {
                return JsonMessage.error("订单不属于该用户!");
            }
            //3.判断order是否支付
            if (courseTrade.getPaymentStatus() == CourseTrade.PaymentStatus.paid) {
                return JsonMessage.error("订单已支付!");
            }

            //4.使用积分支付
            GlobalConfig globalConfig = globalConfigService.getUniqueness();
            if (globalConfig != null) {
                if (globalConfig.getPercentage() != null) {
                    //需要支付的积分
                    BigDecimal point = courseTrade.getPrice().multiply(globalConfig.getPercentage());
                    if (member.getPoint().compareTo(point) >= 0) {  //积分足够
                        member.setPoint(member.getPoint().subtract(point));
                        memberService.update(member);
                        //生成财务记录
                        courseTradeService.dealCourseTradeByPoint(courseTrade);
                    } else {
                        return JsonMessage.error("积分不足");
                    }
                } else {
                    return JsonMessage.error("支付失败");
                }
            } else {
                return JsonMessage.error("支付失败");
            }
            return JsonMessage.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 充值
     * @param receipt
     * @param price
     * @return
     */
    @RequestMapping(value = "/charge", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage verifyReceipt1(String receipt, BigDecimal price) throws Exception {
        receipt = receipt.replaceAll(" ", "+");
        if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
            return JsonMessage.error("请输入充值的金额");
        }
        JSONObject jsonObject = verifyReceipt1("https://buy.itunes.apple.com/verifyReceipt", receipt);
        if (jsonObject != null) {
            if (jsonObject.getInteger("status") == 0) {
                Member member = memberService.getCurrentByToken();
                GlobalConfig globalConfig = globalConfigService.getUniqueness();
                //充值前积分
                BigDecimal prePoint = member.getPoint();
                member.setPoint(prePoint.add(price.multiply(globalConfig.getPercentage())));
                memberService.update(member);
                //充值记录
                tradeService.createTrade(member, price, Trade.Style.pay, prePoint);
                return JsonMessage.success();
            }
        }
        return JsonMessage.error("充值失败");
    }

    public JSONObject verifyReceipt1(String url, String receipt) {
        try {
            HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setAllowUserInteraction(false);
            PrintStream ps = new PrintStream(connection.getOutputStream());
            ps.print("{\"receipt-data\": \"" + receipt + "\"}");
            ps.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            StringBuffer sb = new StringBuffer();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
            String resultStr = sb.toString();
            JSONObject result = JSONObject.parseObject(resultStr);
            System.out.println("首次验证：" + result);
            if (result != null && result.getInteger("status") == 21007) {
                return verifyReceipt1("https://sandbox.itunes.apple.com/verifyReceipt", receipt);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
